/**
 * Copyright (C) 2010 Cloudfarming <info@cloudfarming.nl>
 *
 * Licensed under the Eclipse Public License - v 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.eclipse.org/legal/epl-v10.html
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package nl.cloudfarming.client.sensor.area;

import com.vividsolutions.jts.geom.Geometry;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import nl.cloudfarming.client.logging.AppLogFactory;
import nl.cloudfarming.client.logging.AppLogger;
import nl.cloudfarming.client.model.Field;
import nl.cloudfarming.client.model.SensorData;
import nl.cloudfarming.client.model.SensorDataFile;
import nl.cloudfarming.client.model.SensorRun;
import nl.cloudfarming.client.util.GeometryUtil;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.util.Cancellable;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;

/**
 * Task for linking sensor data to a specific field
 * 
 * @author Timon Veenstra
 */
public class LinkSensorFieldTask implements Callable<Object> {

    private static final AppLogger LOG = AppLogFactory.getLogger(LinkSensorFieldTask.class);
    private final Field field;
    private SensorAreaService service;
    private static final int CACHE_SIZE = 1000;
    private Cancellable cancellable;
    
    LinkSensorFieldTask(Field field) {
        this.field = field;
    }

    @Override
    public Object call() throws Exception {
        try{
        Geometry plotGeometry = GeometryUtil.wktToGeometry(field.getWKT());
        // Find all sensordata within the bounds of the maximum dimensions of the plot
        List<SensorData> sensorData = getService().findUnlinkedSensorDataInBox(plotGeometry.getEnvelope());
        LOG.log(Level.FINE, "{0} entries of sensor data found within envelope {1}", new Object[]{sensorData.size(),plotGeometry.getEnvelope().toText()});

        int progress = 0;
        List<SensorData> sensorDataCache = new ArrayList<SensorData>();
        InternalProgressHandle progressHandle = createProgressHandle();
        progressHandle.start(sensorData.size());
        LOG.log(Level.FINE,"progress handle started for linking sensor data to field {0}",field.getName());
        for (SensorData sd : sensorData) {

            Geometry point = GeometryUtil.getPoint(sd.getLongitude(), sd.getLatitude());

            //
            // check intersection with real plot geometry
            //
            if (plotGeometry.intersects(point)) {
                sd.setSensorRun(getSensorRun(field, sd.getDataSensorFile()));
                sensorDataCache.add(sd);
                if (sensorDataCache.size() % CACHE_SIZE == 0) {
                    LOG.log(Level.FINE,"persisting sensor data cache");
                    service.persist(sensorDataCache);
                    sensorDataCache.clear();
                }
            }
            progressHandle.progress();
        }
        if (!sensorDataCache.isEmpty()) {
            LOG.log(Level.FINE,"persisting remaining sensor data cache");
            service.persist(sensorDataCache);
            sensorDataCache.clear();
        }
        LOG.log(Level.FINE,"link process finished for field {0}",field.getName());
        progressHandle.finish();

        // Clear list
        sensorData.clear();
        }catch(Throwable t){
            LOG.error(t.toString());
            throw new Exception(t);
        }
        return null;
    }

    public void setCancellable(Cancellable cancellable) {
        this.cancellable = cancellable;
    }

    private SensorRun getSensorRun(Field plot, SensorDataFile<?> sensorDataFile) {
        SensorRun run = getService().findSensorRunForPlotAndFile(plot, sensorDataFile);
        if (run == null) {
            run = new SensorRun(sensorDataFile, plot);
            service.newSensorRun(run);
        }
        return run;
    }

    public SensorAreaService getService() {
        if (service == null) {
            service = Lookup.getDefault().lookup(SensorAreaService.class);
        }
        if (service == null) {
            service = new SensorAreaService();
        }
        return service;
    }

    public void setService(SensorAreaService service) {
        this.service = service;
    }
    
    InternalProgressHandle createProgressHandle(){
        return new InternalProgressHandle();
    }
    
    /**
     * internal progress handle to make interception possible
     */
    public class InternalProgressHandle{
        private ProgressHandle intern;
        private int total;
        private int progress = 0;

        public InternalProgressHandle() {
            intern = ProgressHandleFactory.createHandle(NbBundle.getMessage(LinkSensorTask.class, "link.process.plot.title", field.getName()), cancellable);
        }
        
        public void start(int workunits){
            total = workunits;
            intern.start(workunits);
        }
        
        public void progress(){
            if (progress != total){
                intern.progress(++progress);
                LOG.log(Level.FINE,"incrementing total progress to {0}",progress);
            }
        }        
        
        public void finish(){
            intern.finish();
        }        
    }
}
